import React, { useEffect, useState, useCallback } from 'react'
import { connect } from 'react-redux'
import { NotifyType, RecordMode } from '../../common/enums'
import {
    getStepCollectionActiveStepCollectionIdSelector, getSuiteForceReloadIndexSelector,
    getStepCollectionActiveStepCollectionSelector, getStepCollectionActiveStepCollectionModeSelector,
} from '../../selectors/baseSelector'
import { genStepCollectionSetActiveStepCollection } from '../../actions/home'
import { SingleSelectableList } from '../layout/singleSelectableList'
import { getAllStepCollections } from '../../source/getData'
import { notify } from '../../source/notify'
import { genTempId } from '../../source/genTempId'
import { Msgs } from '../../consts/msgs'
import basicStyle from '../common/basic.scss'
import { EmptyElement } from '../common/emptyElement'
import { mergeStyle } from '../common/mergeStyle'
import classnames from 'classnames'
import { Input } from '../common/Input'
import { ColHeader } from '../common/colHeader'

const maStateToProps = state => {
    return {
        forceReloadIndex: getSuiteForceReloadIndexSelector(state),
        activeStepCollection: getStepCollectionActiveStepCollectionSelector(state),
        acitveStepCollectionId: getStepCollectionActiveStepCollectionIdSelector(state),
        activeStepCollectionMode: getStepCollectionActiveStepCollectionModeSelector(state),
    }
}

const mapDispatchToProps = dispatch => {
    return {
        setActiveStepCollection: stepCollection => dispatch(genStepCollectionSetActiveStepCollection(stepCollection)),
        getAllStepCollections: () => getAllStepCollections(),
    }
}

export const StepCollectionList = connect(maStateToProps, mapDispatchToProps)((props) => {
    const { setActiveStepCollection, forceReloadIndex, getAllStepCollections,
        acitveStepCollectionId, activeStepCollection, activeStepCollectionMode } = props
    const [loading, setLoading] = useState(true)
    const [dataSource, setDataSource] = useState([])
    const [filter, setFitler] = useState({ title: '' })

    const wrapOnSelectItem = useCallback(item => setActiveStepCollection(item), [])

    const onAdd = useCallback(() => {
        const toAddSuit = { id: genTempId(), mode: RecordMode.add, title: Msgs.NotSaved, }
        setDataSource(currentDataSource => [toAddSuit, ...currentDataSource])
        setActiveStepCollection(toAddSuit)
    }, [])

    const onClone = useCallback(() => {
        const toAdd = { ...activeStepCollection, id: acitveStepCollectionId, mode: RecordMode.add }
        setActiveStepCollection(toAdd)
    }, [activeStepCollection, acitveStepCollectionId])

    useEffect(() => {
        setLoading(true)
        setDataSource([])

        getAllStepCollections()
            .then((data = []) => {
                setLoading(false)
                setDataSource(data)
            }).catch(err => {
                setLoading(false)
                notify(NotifyType.error, err)
            })
    }, [forceReloadIndex])

    useEffect(() => {
        if (dataSource.length) {
            setActiveStepCollection(dataSource[0])
        } else {
            setActiveStepCollection({ id: '', title: '', mode: '' })
        }
    }, [dataSource])

    const ifMatchFilter = (stepCollection, { title }) => (title ? stepCollection.title.indexOf(title.trim()) >= 0 : true)
    const visibleStepCollections = dataSource.filter(stepCollection => ifMatchFilter(stepCollection, filter))      // 最终显示

    const getTitle = useCallback(item => item.title, [])

    const cloneAvalibale = acitveStepCollectionId && activeStepCollectionMode === RecordMode.edit

    const onChangeFilter = useCallback((field, value) => setFitler(currentFilter => ({ ...currentFilter, [field]: value })), [])

    const onChangeFilterTitle = useCallback(title => onChangeFilter('title', title), [])

    return loading
        ? <div className={basicStyle.basic_loading} />
        : <React.Fragment>
            <ColHeader title='所有步骤集：' />
            <div className={basicStyle.actions}>
                <button onClick={onAdd}>新增</button>
                <button onClick={cloneAvalibale ? onClone : null} className={mergeStyle(basicStyle, classnames({ disabled: !cloneAvalibale }))}>复制</button>
            </div>

            <div>
                <Input placeholder='筛选标题' value={filter.title} onChange={onChangeFilterTitle} readOnly={false} />
            </div>

            {dataSource.length
                ? <SingleSelectableList activeValue={acitveStepCollectionId} dataSource={visibleStepCollections}
                    getItemValue={item => item.id || item.stepCollectionId} getItemTitle={getTitle}
                    onSelectItem={wrapOnSelectItem} />
                : <EmptyElement />}
        </React.Fragment>
})